from sqlalchemy import Column, BigInteger, String, SmallInteger, Integer, DateTime, Index
from app.config.database import Base
from datetime import datetime
from pydantic import BaseModel, ConfigDict
from typing import Optional

class Permission(Base):
    __tablename__ = "sys_permission"
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="权限ID")
    perm_code = Column(String(100), nullable=False, unique=True, comment="权限编码")
    perm_name = Column(String(100), nullable=False, comment="权限名称")
    perm_type = Column(SmallInteger, nullable=False, comment="权限类型：1-菜单 2-按钮 3-接口")
    parent_id = Column(BigInteger, nullable=False, default=0, comment="父权限ID")
    resource_path = Column(String(200), comment="资源路径")
    status = Column(SmallInteger, nullable=False, default=1, comment="状态：0-禁用 1-启用")
    sort_order = Column(Integer, nullable=False, default=0, comment="排序")
    create_time = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    
    # 索引
    __table_args__ = (
        Index('uk_perm_code', 'perm_code'),
        Index('idx_parent_id', 'parent_id')
    )

class PermissionInDB(BaseModel):
    id: int
    perm_code: str
    perm_name: str
    perm_type: int
    parent_id: int = 0
    resource_path: Optional[str] = None
    status: int = 1
    sort_order: int = 0
    create_time: Optional[datetime] = None
    update_time: Optional[datetime] = None

    model_config = ConfigDict(from_attributes=True)